using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Gj.Galaxy.Logic;
using TapSDK.Compliance;
using TapSDK.Core;
using TapSDK.Login;
using UnityEngine;

namespace Gj.TapTap
{
    public class User : SocialManager.PlatformAuth
    {
        private static readonly User instance;
        private static readonly User instanceIo;
        private static readonly User instanceCn;
        // private static readonly Dictionary<string, TDSUser> UserMap = new();
        private SocialManager.Platform Platform;

        static User()
        {
            instance = new User();
            instanceIo = new User();
            instanceIo.Platform = SocialManager.Platform.TapIo;
            instanceCn = new User();
            instanceCn.Platform = SocialManager.Platform.TapCn;
        }

        public async void IsAuthorized(SocialManager.AuthDelegate callback)
        {
            //try {
                TapTapAccount account = await TapTapLogin.Instance.GetCurrentTapAccount();
                if (account == null) {
                    // 用户未登录
                    callback(Platform, 0, null);
                } else {
                    // 用户已登录
                    var dic = new Dictionary<string, string>();
                    dic["nickName"] = Convert.ToString(account.name); // 昵称
                    dic["avatar"] = Convert.ToString(account.avatar);
                    dic["accessToken"] = account.accessToken.ToJson();

                    dic["openId"] = account.openId;
                    dic["unionId"] = account.unionId;
                    // 进入游戏
                    callback(Platform, SocialManager.SUCCESS, dic);

                    // 设置用户 ID 及账号登录事件属性
                    TapTapEvent.SetUserID("tap:"+account.unionId, "");
                }
            //} catch (Exception e) {
            //    Debug.Log($"获取用户信息失败 {e.Message}");
            //    callback(Platform, 0, null);
            //}
        }

        public async void Authorize(SocialManager.AuthDelegate callback)
        {
            try
            {
                // 定义授权范围
                List<string> scopes = new List<string>
                {
                    TapTapLogin.TAP_LOGIN_SCOPE_PUBLIC_PROFILE
                };
                // 发起 Tap 登录
                var userInfo = await TapTapLogin.Instance.LoginWithScopes(scopes.ToArray());
                Debug.Log($"登录成功，当前用户 ID：{userInfo.unionId}");

                var dic = new Dictionary<string, string>();
                dic["nickName"] = Convert.ToString(userInfo.name); // 昵称
                dic["avatar"] = Convert.ToString(userInfo.avatar);
                dic["accessToken"] = userInfo.accessToken.ToJson();

                dic["openId"] = userInfo.openId;
                dic["unionId"] = userInfo.unionId;
                callback(Platform, SocialManager.SUCCESS, dic);
            }
            catch (TaskCanceledException)
            {
                Debug.Log("用户取消登录");
                callback(Platform, 0, null);
            }
            catch (Exception exception)
            {
                Debug.Log($"登录失败，出现异常：{exception}");
                callback(Platform, 0, null);
            }
        }

        public async void Real(SocialManager.RealDelegate callback)
        {
            // var currentUser = await TDSUser.GetCurrent();
            // 获取登录状态
            try
            {
                TapTapAccount account = await TapTapLogin.Instance.GetCurrentTapAccount();
                Debug.Log("已登录");
                await Task.Delay(1000);
                Antiaddiction.Valid(account, info =>
                {
                    Debug.Log("实名制");
                    AuthConnect.realInfo = new RealInfo()
                    {
                        NeedReal = info == null,
                        NeedRefresh = false,
                        Duration = info == null ? 0 :info.RemainingTime,
                        IsUnderAge = info == null ? false : info.IsUnderAge,
                        IsMoreTime = info == null ? false : info.IsMoreTime,
                    };
                    if (info == null)
                    {
                        callback(Platform, 0, "");
                    }
                    else
                    {
                        // 提交服务端
                        callback(Platform, SocialManager.SUCCESS, "");
                    }
                });
            }
            catch (Exception e)
            {
                Debug.Log("当前未登录");
                callback(Platform, 0, "");
            }

            // 获取用户信息
            // var profile = await TapLogin.GetProfile();
            // Antiaddiction.Valid(profile, info =>
            // {
            //     AuthConnect.realInfo = new RealInfo()
            //     {
            //         NeedReal = info == null,
            //         NeedRefresh = false,
            //         Duration = info == null ? 0 :info.RemainingTimeInMinutes,
            //         IsUnderAge = info == null ? false : info.IsUnderAge,
            //         IsMoreTime = info == null ? false : info.IsMoreTime,
            //     };
            //     if (info == null)
            //     {
            //         callback(Platform, 0, "");
            //     }
            //     else
            //     {
            //         // 提交服务端
            //         callback(Platform, SocialManager.SUCCESS, "");
            //     }
            //
            // });
        }

        public void SubmitLeaderboard(string key, int value, SocialManager.LeaderboardDelegate callback)
        {
            throw new NotImplementedException();
        }

        public void AddAchievement(string key, int value, SocialManager.AchievementDelegate callback)
        {
            throw new NotImplementedException();
        }

        public bool CanLocalShare()
        {
            return false;
        }


        public void DirectShare(string title, string imagePath, string description, string targetUrl, string videoUrl,
            SocialManager.ShareDelegate callback)
        {
            throw new NotImplementedException();
        }

        public void Logout(SocialManager.LogoutDelegate callback)
        {
            // await TDSUser.Logout();
            Debug.Log("TapTap Logout");
            callback(Platform);
            TapTapLogin.Instance.Logout();
            Antiaddiction.Exit();
            TapTapEvent.ClearUser();
        }

        public static SocialManager.PlatformAuth Auth(SocialManager.Platform platform)
        {
            switch (platform)
            {
                case SocialManager.Platform.TapCn:
                    return instanceCn;
                case SocialManager.Platform.TapIo:
                    return instanceIo;
            }

            return instance;
        }
    }
}